

#include "main.h"
//#include "AT_Commands.h" 

/* $Id: ModemService.c 12 2013-10-09 10:10:50Z dima.development $ */

//unsigned char RegistrationStep = REGISTRATION_RESET;

/* Modem Types */

//unsigned char ModemType = 0;
unsigned char RSSI = 0;
//unsigned int Delay;
unsigned char near ModemStatus = 0;
//near bit LCC_UPDATED;
//near bit SMS_FULL;
//near bit DATA_MODE;

near bit User_Message;
near bit No_Delete_SMS_For_User;

unsigned char SMS_Monitor_State = 0;

#ifdef	MODEM_TYPE__TELIT
unsigned char Start_CLCC = 0;
#endif

//unsigned char NEW_USER_SMS = 0; /* New SMS and contain amount of unread SMS */

//unsigned char SMS_Monitor_Status = 0;

unsigned char SMS_User_Messages_List[SMS_FOR_EXT_USER_MAX];

//unsigned char Active_IMSI[16];

/* unsigned char SMS_User_New_Messages[SMS_FOR_USER_MAX];	/\* numbers of new SMS message  *\/ */
/* unsigned char pSMS_User_New_Messages = 0; */

//unsigned char SMS_User_New_Message_Count = 0;
//unsigned char SMS_User_Ext_New_Message_Count = 0;

unsigned char SMS_NotAccepted[8];
unsigned char pSMS_NotAccepted = 0;

//unsigned char SMS_User_Free_Entry = SMS_FOR_USER_MAX;

unsigned char SMS_Delete[SMS_FOR_USER_MAX*2];
unsigned char pSMS_Delete = 0;

unsigned char SMS_Buffer[SMS_BUFFER_SIZE];	/* Download buffer of SMS message */

unsigned char SMS_Monitor_Cycle; /* in sec */

//unsigned char SMS_Monitor_State = 0;

//unsigned char bank1 SMS_StoreAmount = 0;  unsigned
SMS_HEADER SMS_Header;
//LIST_CURRENT_CALLS ListCurrentCalls;

const char* Parameters[] =
{
	"ATE0\r",						  /* echo OFF */
	"ATE0\r",						  /* echo OFF */
//SMS in TEXT mode;extended format reporting.Example instead of "RING" "+CREG: VOICE";
//SMS with indication(1) full indication + message(2)
	"AT+CMGF=1;+CRC=1;+CNMI=,1\r",
	"AT+CGSN\r",

#ifndef   WITHOUT_SIM

#ifdef   MODEM_TYPE__SIMCOM
	"AT+CMGDA=\"DEL READ\"\r",
#else
	"AT+CMGD=1,4\r",
#endif

#endif
	
	"AT+CLIP=1\r",

/* #if defined(MODEM_TYPE__SIMCOM) */
/* 	"AT+CENG=1\r",					  /\* neighbouring cells *\/ */
/* #endif */

	"END"
};


void SMS_Delete_Message( unsigned char MesNum );
unsigned char* DateFormat( unsigned char* Str );
//unsigned char* Modem_GetRealTimeClock( unsigned char*, unsigned int  );
unsigned char RequestToModem ( const char* Request, const char* ExpectedResponse );

/* Reguest to modem */
 
#define   RTM_RESET				0
#define   RTM_RESET_2			1
#define   REQUEST_TO_MODEM		2
#define   WAIT_FOR_ANSWER		3
#define   DELAY					4

#define   STM_RESET  0
//bit NEW_SMS_MESSAGE = 0;
//bit SEND_MESSAGE_BUSY = 0;


/* Variants of Response  */
/* TRUE - if Request == ExpectedResponse; FALSE - if not*/

//unsigned char Temp_Str[40]; 		  /* ATD + PhoneNumber(18chars) + CR + 0 */
unsigned char DateAndTime[30];

unsigned char CellNetwork_Event = 0xFF, CellNetwork_Status;

unsigned char CellNetwork_Reg_Monitor_cycle = 200;

void CellNetwork_RSSI ( void )
{
	static unsigned char Delay = 16;
	unsigned char Response;
	unsigned int temp;

	if ( Delay )
	{
		if ( Time_1000ms )
		{
			Delay--;
		}

		return ;
	}


	Response = SendToModem("AT+CSQ\r", STR__OK, BUSY_NETWORK_RSSI ); 

	if ( Response != BUSY )
	{
		if ( Response == TRUE )
		{  
			temp = StrToLong(ModemRecBuffer);
			if ( temp != -1 )
			{
				temp *= 100;
				temp /= 31;
				RSSI = (unsigned char)temp;
				Debug("\n\n=== RSSI: %d%%\n\n",RSSI);
			}

		}

		Delay = 16;
	}
}

unsigned char cell_net_err_cnt;

void CellNetwork_Reg_Monitor ( void )
{
	unsigned char Response;

	CellNetwork_Event = 0;

	if ( CellNetwork_Reg_Monitor_cycle )
	{
		if ( Time_1000ms )
		{
			CellNetwork_Reg_Monitor_cycle--;
		}

		return ;
	}

	Response = SendToModem("AT+CREG?\r", STR__OK, BUSY_NETWORK_REG_MONITOR ); 

	if ( Response != BUSY )
	{
		if ( Response == TRUE )
		{  
			Debug("\r\nModemRecBuffer: %s\n", ModemRecBuffer);
#ifdef   MODEM_TYPE__SIMCOM                 
			if ( !StrCmp( "+CREG: 0,1", ModemRecBuffer ) || 
				  !StrCmp( "+CREG: 0,5", ModemRecBuffer ))
#else						
			if ( !StrCmp( "+CREG: 000,001", ModemRecBuffer ) || 
				  !StrCmp( "+CREG: 000,005", ModemRecBuffer ))
#endif
			{
				CellNetwork_Event = CELL_NETWORK__REGISTRATION_OK;	
				RegistrationStatus.REGISTERED = TRUE;
			}
			else
			{
				CellNetwork_Event = CELL_NETWORK__NO_REGISTRATION;
				RegistrationStatus.REGISTERED = FALSE;
				dbg("\ncell_net_err_cnt: %d\n",cell_net_err_cnt); //Dima
				if ( ++cell_net_err_cnt > 3 )
				{
					cell_net_err_cnt = 0;
					SysState = MODEM_RESET_POWER_DOWN;
				} 
			}
		}
		else
		{
			CellNetwork_Event = CELL_NETWORK__MODEM_ERROR;
		}

		if ( RegistrationStatus.REGISTERED )
		{
			CellNetwork_Reg_Monitor_cycle = 11;

		}	
		else
		{
			CellNetwork_Reg_Monitor_cycle = 3;
		}
		
		if ( CellNetwork_Status != CellNetwork_Event )
		{
			CellNetwork_Status = CellNetwork_Event;
			
			Debug("\n CellNetwork_Reg_Monitor: %d", CellNetwork_Event);
		}
	}
}


unsigned char SendToModem ( const char* Request, const char* ExpectedResponse, unsigned char Signature )
{
	static unsigned char Step = 0, TryIfNotResponse = 0, ExpectedResponse_Size = 0;
	static unsigned char TimeOut = 0;
	unsigned char str[36];	//AT+CMGS="0525620534",129
	unsigned char *p;

	if ( ModemStatus == READY )
	{
		ModemStatus = Signature;
		Step = STM_RESET;
	}
	else
		if ( ModemStatus != Signature ) 
		{
			return BUSY;
		}

	switch ( Step )
	{
		case STM_RESET:
			TimeOut = 5;
			TryIfNotResponse = 3;
			ExpectedResponse_Size = StrLen(ExpectedResponse);
			Step = REQUEST_TO_MODEM;
			break;
			
		case REQUEST_TO_MODEM:
			if ( !StrCmp(Request, "AT+CMGS=") || errno == 8)
			{
				p = StrCpy_UpTo_Ch(str, Request, '\r');
				StrCat(str, "\r");
				putsf(str, MODEM_PORT);
				delay_ms(250);
				putsf(p, MODEM_PORT);
			}
			else	
			{  
				putsf( Request, MODEM_PORT );
			}
			
			if ( ExpectedResponse == NULL )
			{
				Step = STM_RESET;
				ModemStatus = READY;
				return TRUE;
			}

			Step = WAIT_FOR_ANSWER;

			break;

		case WAIT_FOR_ANSWER:
			if ( ModemEvents == MODEM_NEW_MESSAGE_COMPLETE )
			{
				Step = STM_RESET;
				ModemStatus = READY;
				
/* 				if ( ExpectedResponse[0] == '?' ) */
/* 				{ */
/* 					return TRUE;  */
/* 				} */
/* 				else */
				if ( StrCmp(STR__OK, ExpectedResponse) == 0 )
				{
					return TRUE;
				}
				else
					if ( !StrCmp(ExpectedResponse, ModemRecBuffer) || ExpectedResponse_Size == errno )
					{
						return TRUE;
					}
					else
					{
						return FALSE;
					}
			}
			else
				if ( ModemEvents == MODEM_ERROR )
				{
					Step = STM_RESET;
					ModemStatus = READY;
					return FALSE;
				}
				else
					if ( ModemEvents == NO_CARRIER )
					{
						Step = STM_RESET;
						ModemStatus = READY;
						return NO_CARRIER;
					}
					else
					{
						if ( Time_1000ms && --TimeOut == 0 )
						{
							if ( --TryIfNotResponse == 0 )
							{
								Step = STM_RESET;
								ModemStatus = MODEM_NOT_ANSWER;
								return FALSE; //MODEM_NOT_ANSWER;
							}	
							else
							{
								TimeOut = 3;
								Step = REQUEST_TO_MODEM;
							}
						}
					}

			break;
	

		default:
			;
	}

	return BUSY;
}

//+CCLK: 06/11/29,08:40:09	/TELIT
//+CCLK: "06/11/29,08:42:04+08"
unsigned char* DateFormat( unsigned char* Str )
{
	unsigned char temp_1, temp_2;

#ifdef	MODEM_TYPE__TELIT   
	temp_1 = Str[0];
	temp_2 = Str[6];
	Str[0] = temp_2;
	Str[6] = temp_1;

	temp_1 = Str[1];
	temp_2 = Str[7];
	Str[1] = temp_2;
	Str[7] = temp_1;

/* 	Str[9] = 0; */
/* 	Str[15] = 0; */
/* 	Str[16] = ' '; */
/* 	Str[17] = ' '; */
/* 	Str[18] = ' '; */
/* 	Str[19] = ' '; */
/* 	Str[20] = ' '; */
/* 	Str[21] = 0;					   */

	Str[8] = 0;
	Str[14] = 0;
	Str[15] = ' ';
	Str[16] = ' ';
	Str[17] = ' ';
	Str[18] = ' ';
	Str[19] = ' ';
	Str[20] = 0;

	StrCat( (Str+15), Str+0 );	  /* Move Date to Temp*/
	
	Str[0] = ' '; 
	Str[1] = 0;
	StrCat( Str, (Str+9) );	  /* Move Time */

	StrCat( Str, (Str+15) );	  /* Add Date from Temp*/
#else
	temp_1 = Str[1];
	temp_2 = Str[7];
	Str[1] = temp_2;
	Str[7] = temp_1;

	temp_1 = Str[2];
	temp_2 = Str[8];
	Str[2] = temp_2;
	Str[8] = temp_1;

	Str[9] = 0;
	Str[15] = 0;
	Str[16] = ' ';
	Str[17] = ' ';
	Str[18] = ' ';
	Str[19] = ' ';
	Str[20] = ' ';
	Str[21] = 0;					  

	StrCat( (Str+16), Str+1 );	  /* Move Date to Temp*/
	
	Str[0] = ' '; 
	Str[1] = 0;
	StrCat( Str, (Str+10) );	  /* Move Time */

	StrCat( Str, (Str+16) );	  /* Add Date from Temp*/
#endif

	return Str; 
}

unsigned char Modem_GetRealTimeClock( unsigned char* DateTime, unsigned char Period  )
{
	/* +CCLK: "06/03/29,10:25:09+08" */

	unsigned char Response; //str[12];
	static unsigned char Cycle = 3;
	static unsigned char State = 0;
	

	switch ( State )
	{
		case 0:						  /* Cycle */
			if ( Time_1000ms && --Cycle == 0 )
			{
				Cycle = Period;
				State++;
			}
			break;
			
		case 1:						  /* Wait for Modem */
			Response = SendToModem( "AT+CCLK?\r", STR__OK, BUSY_RT_CLOCK );	//+CCLK: "06/08/02,11:26:25+12"
			if ( Response != BUSY )
			{
				State = 0;
				
				if ( Response == TRUE )
				{
					StrCpy( DateTime, ModemRecBuffer+7);
					DateFormat( DateTime );
					return TRUE; 
				}
			}

			break;

		default: 
			;
	}

	return BUSY; 
}
 

unsigned char Get_RSSI ( unsigned char Period )
{
	static unsigned char Step = 0;
	static unsigned int Cycle = 9;
	unsigned char Response; 
	int temp = 0; 


	switch ( Step )
	{
		case 0:
			if ( Time_1000ms && --Cycle == 0 ) 
			{
				Cycle = Period;
				Step++;
			}
			else
			{
				break;			
			}

		case 1:
			Response = SendToModem("AT+CSQ\r", STR__OK, BUSY_RSSI_MANAGER );
			if ( Response != BUSY )
			{
				Step = 0;
				
				if ( Response == TRUE )
				{
					temp = StrToLong(ModemRecBuffer);
					if ( temp != -1 )
					{
						temp *= 100;
						temp /= 31;
						RSSI = (unsigned char)temp;
					}

					return RSSI_UPDATED; 
				}
				
				return FALSE;
			}
			break;


		default: 
			;
	}

	return BUSY; 	
} 

unsigned char ErrCnt;
 
unsigned char Registration( void )
{
	static unsigned char State = 0, NextState, Delay = 10, AT_Command_Number = 0;
	unsigned char Response;
	
	switch ( State )
	{
		case 0:
		if ( !StrCmp("END", Parameters[AT_Command_Number]) )
		{
			AT_Command_Number = 0;
			
#ifdef	WITHOUT_SIM   			
			State = 3;				  /* do delay end exit from registration */
			Delay = 2;
			NextState = 4;
#else
			State = 2;				  /* goto gegistration on the network */
			dbg("\n === Modem initialization: OK ===\n Go to Registration...\n"); //Dima
#endif
			ErrCnt = 40;
		}
		else
		{
			dbg("\nParameters[AT_Command_Number]: [%s]\n",Parameters[AT_Command_Number]); //Dima
			State = 1;
		}
		break;
					
		case 1:
			Response = SendToModem( Parameters[AT_Command_Number], STR__OK, BUSY_NETWORK_REGISTRATION );
			if ( Response != BUSY )
			{
				if ( Response == TRUE )
				{
					AT_Command_Number++;
					State--;
				}
				else
				{
					State = 3;
					Delay = 2;
					NextState = 0;
					
					if ( ++ErrCnt > 5 )
					{
						AT_Command_Number = 0;
						ErrCnt = 0;
						State = 0;
						return FAIL;
					}
				}
			}
			break;

		case 2:
			Response = SendToModem("AT+CREG?\r", STR__OK, BUSY_NETWORK_REGISTRATION ); 
			if ( Response != BUSY )
			{
				Debug("\nModemRecBuffer: %s\n",ModemRecBuffer);
				if ( Response == TRUE )
				{  
#ifdef   MODEM_TYPE__SIMCOM                 
					if ( !StrCmp( "+CREG: 0,1", ModemRecBuffer ) || 
						  !StrCmp( "+CREG: 0,5", ModemRecBuffer ))
#else						
					if ( !StrCmp( "+CREG: 000,001", ModemRecBuffer ) || 
						!StrCmp( "+CREG: 000,005", ModemRecBuffer ))
#endif
					{
						
						State = 4;
						break;
					}
				}

				if ( --ErrCnt == 0 )
				{
					State = 0;
					return FAIL;
				}
				else
				{
					Delay = 3;
					NextState = 2;
					State = 3;
				}
			}
			break;

		case 3:
		   if ( Time_1000ms && --Delay == 0 )
			{
				State = NextState;
			}
			break;

		case 4:						  /* Exit */
			State = 0;
			RegistrationStatus.REGISTERED = TRUE;
			return TRUE;
		
		default :
			State = 0;
			
	}

	return BUSY;
}

// INCOMING
//        7 9 11 13 15  18        28 30
/* +CLCC: 1,1,4, 0, 0, "0542162370", 129,"" */

#define   IN_VOICE	1
#define   IN_DATA		2


unsigned char IncomingCall_Event;
 
void IncomingCallMonitor( void )
{
	static unsigned char State = 0;
	unsigned char str[14];
	unsigned char strBCD[PHONE_NUMBERS_BCD_SIZE];
	unsigned int Address;

	IncomingCall_Event = FALSE;

	switch (  State )
	{
		case 0:
			if ( ModemEvents == MODEM_NEW_MESSAGE_PART )
			{
				// +CLIP: "0523974963",129,"",128,"",0
				// +CLIP: "",129,"",,"",00
				if ( !StrCmp("+CLIP: \"", ModemRecBuffer) || errno == 8 )
				{
					Debug("\nICM: ModemRecBuffer: %s", ModemRecBuffer);
					//Debug(">> INCOMING CALL:",0);
					StrCpy_UpTo_Ch(str, &ModemRecBuffer[8], '"');
					Debug("\nPhone: %s", str);

					StrToBCD(strBCD, str, PHONE_NUMBERS_BCD_SIZE);
					/* Debug("\nstrBCD: %x %x %x %x %x %x %x", strBCD[0], strBCD[1], strBCD[2], strBCD[3],  */
					/* 		strBCD[4], strBCD[5], strBCD[6]); */

					FlipFlopN(strBCD, PHONE_NUMBERS_BCD_SIZE);
					/* Debug("\nstrBCD: %x %x %x %x %x %x %x", strBCD[0], strBCD[1], strBCD[2], strBCD[3],  */
					/* 		strBCD[4], strBCD[5], strBCD[6]); */

					
					Address = Ex_Entry_Find( DIRECTORY__USER_LIST_1, strBCD, 4);
			
					if ( Address != EX_ERROR )
					{
						Debug("\nICM: PHONE FOUND; ADDRESS: 0x%X", Address );
						
						IncomingCall_Event = INCOMING_CALL_EVENT__PHONE_FOUND;  

#if defined(APP_FOR_AMIR) || defined(APP_COMMAND_TRANSLATOR)
						OUT_1 = 30;	  /* 30 * 100ms */
#endif
					}
					else
					{
						Debug("\nICM: PHONE NOT FOUND;" );
						IncomingCall_Event = INCOMING_CALL_EVENT__PHONE_NOT_FOUND;  
					}

					Debug("\nEx_Global = %d", Ex_Global);
					State++;
				}

				
			}
			break;


		case 1:
			if ( SendToModem("ATH\r", STR__OK, BUSY_INCOMING_CALL_MONITOR) != BUSY )
			{
				State = 0;
			}
			break;

		default:
			State = 0;
	}
}
                              //         7 9 B D F 11
/* void CallStatusMonitor( void ) /\* +CLCC: 1,1,4,0,0,"0542162370",129,""; +CRING: VOICE *\/ */
/* {										  //+CLCC: 1,1,6,0,0,"0523975291",129,"" /MOTOROLA */
/* 										  //+CLCC: 1,0,0,0,0,"0523974963",129    /TELIT */
/* 	LCC_UPDATED = FALSE; */

/* #ifdef MODEM_TYPE__TELIT	    */

/* 	if ( Start_CLCC ) */
/* 	{ */
/* 		//Response = SendToModem("AT+CLCC\r", STR__OK, BUSY_TELIT_CLCC);   */
/* 		if ( SendToModem("AT+CLCC\r", STR__OK, BUSY_TELIT_CLCC) != BUSY ) */
/* 		{ */
/* 			if ( Start_CLCC == IN_VOICE ) */
/* 			{ */
/* 				Start_CLCC = FALSE; */
/* 				goto NOTIFY; */
/* 			} */
/* 			Start_CLCC = FALSE; */
/* 		}  */
/* 	} */

/* 	if ( ModemEvents == NO_CARRIER ) */
/* 	{ */
/* 		ListCurrentCalls.CallState = RELEASED; */
/* 		goto REL; */
/* 	} */

/* #endif				 */
	
/* 	if ( ModemEvents == MODEM_NEW_MESSAGE_PART ) */
/* 	{ */
/* 		if( !StrCmp("+CLCC", ModemRecBuffer) || errno == 5 ) */
/* 		{ */
/* 			LCC_UPDATED = TRUE; */
/* 			ListCurrentCalls.CallState = ModemRecBuffer[11]; */
/* 			ListCurrentCalls.Mode = ModemRecBuffer[13]; */
/* 			ListCurrentCalls.NumberType = StrToLong(ModemRecBuffer+30); */
/* 			//MemCpy(ListCurrentCalls.PhoneNumber, (ModemRecBuffer +18), 10 ); */
/* 			StrCpy_UpTo_Ch(ListCurrentCalls.PhoneNumber, (ModemRecBuffer +18), '"' ); */
/* 			//ListCurrentCalls.PhoneNumber[10] = 0; */
			
/* 			//puts(ModemRecBuffer, AUX_PORT); */
/* #ifdef	MODEM_TYPE__TELIT   			 */
/* 		  REL:	 */
/* 			//lcd_print_str("D",15,3,0);	 */
/* #endif */
/* 			if ( SysState == CONVERSATION || SysState == CONNECTED_VOICE ||  */
/* 				  PrevState == CONVERSATION || PrevState == CONNECTED_VOICE ) */
/* 			{ */
/* 				if ( ListCurrentCalls.CallState == RELEASED ) */
/* 				{ */
/* 					if ( !StrCmp(ListCurrentCalls.PhoneNumber, PhoneNumber) ) */
/* 					{ */
/* 						if ( SysState == CONNECTED_VOICE ) */
/* 							SysState = DISCONNECTED_VOICE; */
/* 						else */
/* 							if ( SysState == CONVERSATION ) */
/* 								SysState = IDLE; */
/* 							else */
/* 								if ( PrevState == CONNECTED_VOICE ) */
/* 									NextState = DISCONNECTED_VOICE; */
/* 								else */
/* 									if ( PrevState == CONVERSATION ) */
/* 										NextState = IDLE; */
/* 					}		 */
/* 				} */

/* /\* 				else *\/ */
/* /\* 					if ( ListCurrentCalls.CallState == WAITING ) *\/ */
/* /\* 					{ *\/ */
/* /\* 						ModemSet("AT+CHLD=0\r", STR__OK); /\\* kill the incoming call *\\/ *\/ */
/* /\* 					} *\/ */
/* 			} */
/* 		} */
/* 		else */
/* 			if ( !StrCmp("+CRING: VOICE", ModemRecBuffer) ) */
/* 			{ */
/* 				if ( SysState != MODEM_DISCONNECT) */
/* 				{ */
/* #ifdef MODEM_TYPE__TELIT	    */
/* 					Start_CLCC = TRUE; */
/* #else				 */
/* 					goto NOTIFY; */
/* #endif */
/* 				} */
/* 				else */
/* 					if ( SysState == IDLE || SysState == INCOMING_CALL ) */
/* 					{ */
/* #ifdef MODEM_TYPE__TELIT	    */
/* 						Start_CLCC = TRUE; */
/* #else				 */
/* 						goto NOTIFY; */
/* #endif */
/* 					} */
/* 					else */
/* 						if ( SysState == DIAL ) */
/* 						{ */
/* 							SysState = MODEM_DISCONNECT; */
/* 						}					 */
/* 			} */
/* #ifdef	MODEM_TYPE__TELIT */
/* 			else */
/* 				if( !StrCmp("+CRING: DATA", ModemRecBuffer) ) */
/* 				{ */
/* 					Start_CLCC = IN_DATA; */
/* 				} */
/* #endif */

/* 	} */

/* 	return ; */

/*   NOTIFY: */
/* 	//RING(); */
/* 	SysState = INCOMING_CALL; */
/* 	PIN_LCD_BACKLIGHT = TRUE; */
/* } */
 
/* unsigned char Get_VoiceMail_PhoneNumber( unsigned char* VM_PhoneNumber ) */
/* { */
/* 	unsigned char Response, i = 0; */
/* 	Response = SendToModem("AT+CSVM?\r", STR__OK, BUSY_VOICE_MAIL); */
/* 	if ( Response != BUSY ) */
/* 	{ */
/* 		VM_PhoneNumber[0] = 0; */
/* 		if ( Response == TRUE ) */
/* 		{ */
/* 			if ( StrCmp ( "+CSVM: 0", ModemRecBuffer ) != 0 )	/\* if the phone number was writed *\/ */
/* 			{ */
/* 				Response = 10; */
				
/* 				while ( ModemRecBuffer[Response] != '"' ) */
/* 				{ */
/* 					VM_PhoneNumber[i++] = ModemRecBuffer[Response++]; */
/* 				} */
				
/* 				VM_PhoneNumber[i] = 0; */
				
/* 				return TRUE; */
/* 			} */
/* 			else */
/* 			{ */
/* 				return FALSE; */
/* 			} */
/* 		}	 */
/* 	} */

/* 	return BUSY; */
/* } */

unsigned char SMS_Read( unsigned char* Buffer, unsigned char MessageNumber, unsigned char Signature )
{
	static unsigned char Step = 0, Timeout = 0; //, Owner;
	unsigned char t_str[5];
	unsigned char *p;

	if ( ModemStatus == READY )
	{
		ModemStatus = Signature;
		Step = 0;
	}
	else
		if ( ModemStatus != Signature ) 
		{
			return BUSY;
		}

	switch ( Step )
	{
		case 0:
			if ( MessageNumber )
			{
				Timeout = 0;
				putsf("AT+CMGR=", MODEM_PORT );
				LongToStr( t_str, MessageNumber);
				puts( t_str, MODEM_PORT );
				putsf("\r", MODEM_PORT );
				SMS_Header.Data[0] = 0;
				Buffer[0] = 0;
				Step++;
			}
			else
			{
				ModemStatus = READY;
				return ERROR_SMS_NUMBER;
			}

			break;

		case 1:
			if ( ModemEvents == MODEM_NEW_MESSAGE_PART )
			{		
				//+CCLK: "06/05/14,15:33:40+12"
				//   +CMGR: "REC READ","",,"06/09/18,11:26:10+00"
				//   +CMGR: "REC READ","+94786075911",,"06/09/16,13:14:23+00"
				//   +CMGR: "REC READ","+972523974781",,"06/05/14,15:15:49+12"		
				//   +CMGR: "REC READ","+972525628965",,"06/11/16,14:47:24+08" /TELIT
				if ( !StrCmp("+CMGR", ModemRecBuffer ) || errno == 5 )	
				{
					p = StrCpy_UpTo_Ch( SMS_Header.Field.PhoneNumber, (ModemRecBuffer+19), '"'); 
					StrCpy( DateAndTime, p+2);
					StrCpy(SMS_Header.Field.DateTime, DateAndTime);

#ifdef	MODEM_TYPE__TELIT
					DateFormat( DateAndTime+1 );
					DateAndTime[0] = ' ';
#else
					DateFormat( DateAndTime );
#endif
				}
				else
				{
					StrCat(Buffer, ModemRecBuffer);
					StrCat(Buffer, "\r");
				}
					
			}
			else
				if ( ModemEvents == MODEM_NEW_MESSAGE_COMPLETE )
				{
					ModemStatus = READY;
					Step = 0;
					if ( !StrCmp("+CMGR", ModemRecBuffer ) || errno == 5 )	
					{
						StrCpy(Buffer, STR___EMPTY_MESSAGE_);
					}
					return TRUE;
				}
				else
					if ( ModemEvents == MODEM_ERROR || ( Time_10ms && --Timeout == 0 ) )
					{
						//lcd_print_str ( "TIME_OUT", 3,3,0);
						//delay_ms(10);
						ModemStatus = READY;
						Step = 0;
						return FALSE;
					}
					break;

		default: 	
			;
				
	}
	return BUSY;
}
 
void SMS_Monitor( void )		  /* sorting of SMS message - command or SMS for user */
{
	static unsigned int timeout;
	//static unsigned char SMS_Monitor_State = 0, ErrCnt = 0, Header = 0, Modem_ErrCnt = 4;
	static unsigned char ErrCnt = 0, Header = 0, Modem_ErrCnt = 4;
	static unsigned char sms_num = 0, temp_str[20], PingPongNumber[17];
	unsigned char i;

	User_Message = FALSE;
	//dbg("\nSMS_Monitor_State: %d", SMS_Monitor_State); //Dima
	switch ( SMS_Monitor_State )
	{
	  	case 0:
			SMS_Monitor_State++;
			ErrCnt = 0;
			timeout = 0;
			//E2_Str_LoadFrom(temp_str, E2_ADDR_MY_PHONE_NUMBER ) ;	/* don't answer to My SMS*/
			break;
			
		case 1:
			if ( ModemStatus == READY )
			{
				ModemStatus = BUSY_SMS_MONITOR;

				//putsf(" > SMS_M\r", MODEM_PORT );
				LED = 1;

				SMS_Monitor_State++;
			}
			break;

		case 2:
			putsf("AT+CMGL=\"REC UNREAD\"\r", MODEM_PORT );
			SMS_Monitor_State++;
			break;
		
		case 3:
			if ( ModemEvents == MODEM_NEW_MESSAGE_PART )
			{
				dbg("\nModemEvents == MODEM_NEW_MESSAGE_PART\n"); //Dima
				dbg("ModemRecBuffer: %s", ModemRecBuffer); //Dima
				
				if ( !StrCmp("+CMGL", ModemRecBuffer) || errno == 5 )
				{	
					sms_num = StrToLong(ModemRecBuffer);	/* get number of new message */
				}
				else
					if ( ModemRecBuffer[0] != '+' && ModemRecBuffer[1] != 'C' )
					{
						Debug("\rRECEIVED SMS: %s\n", ModemRecBuffer);
						
						if ( !StrCmp("##",ModemRecBuffer) || errno == 2 ) /* Command token */
						{
							AddCommand(sms_num);
							Debug("\rSMS_Command[%d]: %s\n", sms_num, &ModemRecBuffer[2]);
						}
					}
			}
			else
				if ( ModemEvents == MODEM_NEW_MESSAGE_COMPLETE )
				{
					Modem_ErrCnt = 4;
			
					ModemStatus = READY;

					SMS_Monitor_State++;

					dbg("\nModemEvents == MODEM_NEW_MESSAGE_COMPLETE\n"); //Dima
				}
				else
					if ( ModemEvents == MODEM_ERROR )
					{
						SMS_Monitor_Cycle = 3;
						Execute_Module_1 = NULL;
						ModemStatus = READY;
						SMS_Monitor_State = 0;
						if ( Modem_ErrCnt-- == 0 )
						{	dbg("\n ^^^ SMS_Monitor; goto MODEM_RESET\n"); //Dima
							SysState = MODEM_RESET_POWER_DOWN; //RESET();
						}
					}
					else
					{
						if ( ++timeout > 60000 )
						{
							timeout = 0;
							SMS_Monitor_State = 0;
							ModemStatus = READY;
							Execute_Module_1 = NULL;
							SMS_Monitor_Cycle = 10;
							dbg("==========>> SMS_Monitor: timeout"); //Dima
						}
					}
			break;

		case 4:
			if ( pSMS_NotAccepted > 0 )	//Sorry... I'm full and can't accept your message. Please try later.
			{
				pSMS_NotAccepted--;
				SMS_Monitor_State++;
				ErrCnt = 0;
			}
			else
			{
				SMS_Monitor_State += 4;
			}

			break;

		case 5:
			i = SMS_Read( SMS_Buffer, SMS_NotAccepted[pSMS_NotAccepted], BUSY_SMS_MONITOR );
			if ( i != BUSY )
			{
				if ( i == TRUE )
				{
               /* if My Phone and destination Phone is the same Phone, then skip - don't send notice message */
					if ( !E2_StrCmp(SMS_Header.Field.PhoneNumber+4, E2_ADDR_MY_PHONE_NUMBER+1) )
						SMS_Monitor_State--;
					else
						if ( !StrCmp( PingPongNumber, SMS_Header.Field.PhoneNumber+4) )
						{
							SMS_Monitor_State--;
						}
						else
						{
							StrCpy(PingPongNumber, SMS_Header.Field.PhoneNumber+4);
							SMS_Monitor_State++;
						}
				}
				else
				{
					if ( ++ErrCnt > 7 )
					{
						SMS_Monitor_State--;
					}
				}
			}
			break;

		case 6:
			if ( ModemStatus == READY )
			{
				ModemStatus = BUSY_SMS_MONITOR;
				putsf( "AT+CMGS=\"", MODEM_PORT );
				putsf( SMS_Header.Field.PhoneNumber, MODEM_PORT );
				if ( SMS_Header.Field.PhoneNumber[0] == '+' )
					putsf("\",145\r", MODEM_PORT );
				else
					putsf("\",129\r", MODEM_PORT );
				delay_ms(300);
				putsf(STR__SORRY____IM_FULL, MODEM_PORT );
				SMS_Monitor_State++;
			}
			break;	

		case 7:
			if ( ModemEvents == MODEM_NEW_MESSAGE_COMPLETE ) /* Receive STR__OK from modem */
			{
				SMS_Monitor_State -= 3;
				ModemStatus = READY;
			}
			else
				if ( ModemEvents == MODEM_ERROR )
				{
					ModemStatus = READY;
					if ( ++ErrCnt > 3 )
						SMS_Monitor_State -= 3;
					else
						SMS_Monitor_State--;
				}
			break;

		case 8:
			if ( pSMS_Delete )
			{
				StrCpy(temp_str, "AT+CMGD=");
				LongToStr( (temp_str+errno), (unsigned long)SMS_Delete[--pSMS_Delete] );
				StrCat( temp_str, "\r");
				SMS_Monitor_State++;
				ErrCnt = 0;
			}
			else
			{
				if ( ModemStatus == READY )
				{
					//putsf(" > SMS_M_\r", MODEM_PORT );
					LED = 0;
					dbg("\n----->> timeout: %d\n", timeout); //Dima
					if ( pSMS_Commands )
						Execute_Module_1 = Command_Processor;
					else
						Execute_Module_1 = NULL;
					SMS_Monitor_State = 0;
					if ( SMS_Monitor_Cycle == 0)
						SMS_Monitor_Cycle = 4;
				}
			}
			break;

		case 9:						  /* Delete OLD message */
			i = SendToModem(temp_str, STR__OK, BUSY_SMS_MONITOR);
		
			if ( i != BUSY )
			{
			  	if ( i == TRUE )
				{
					SMS_Monitor_State--;
				}
				else
				{
					if ( ++ErrCnt > 2 )
					{
						SMS_Monitor_State--;
					}
				}
			}
			break;

		default: 
			;
	}
}
 
/* Return how many items in the list and fill SMS_List with numbers of received SMS messages*/
unsigned char SMS_Get_List( const unsigned char* Read_UnRead, unsigned char* SMS_List  )
{
	static unsigned char State = 0, i;
	//unsigned char Response;
	
	switch ( State )
	{
		case 0:						  /* Get messages list  */
			if ( ModemStatus == READY )
			{
				ModemStatus = BUSY_SMS_GET_LIST;
				i = 0;
				State++;
			}
			break;

		case 1:
			putsf("AT+CMGL=\"REC ", MODEM_PORT);
			putsf(Read_UnRead, MODEM_PORT);
			putsf("\"\r", MODEM_PORT);
			SMS_List[0] = 0;
			State++;
			break;

		case 2:
			if ( ModemEvents == MODEM_NEW_MESSAGE_PART )
			{
				if ( !StrCmp("+CMGL", ModemRecBuffer) || errno == 5 )
				{
					if ( i < SMS_FOR_EXT_USER_MAX )
					{
						SMS_List[i++] = StrToLong(ModemRecBuffer);
					}
				}
			}
			else
				if ( ModemEvents == MODEM_NEW_MESSAGE_COMPLETE ) /* Receive STR__OK */
				{
					SMS_List[i] = 0;	  /* end of SMS List */
					ModemStatus = READY;
					State = 0;
					return i;
				}
				else
					if ( ModemEvents == MODEM_ERROR )
					{
						ModemStatus = READY;
						State = 0;
						return MODEM_ERROR;
					}

			break;

		default:
			;
	}

	return BUSY;
}

/* 

			Check if customers exists
			if ( Entry_CustomerAmount(LIST_OWNERS) == I2C_ERROR  )
			{
				putsf(" >>I2C_ERROR", MODEM_PORT);
			}
			if ( Entry_CustomerAmount(LIST_OWNERS) != I2C_ERROR  && Entry_CustomerAmount(LIST_OWNERS) != 0 )
				//if ( Entry_CustomerAmount(LIST_OWNERS) != 0 )
			{
				if ( SMS_Sender_Manager__SendTo == LIST_OWNERS )
				{
					Amount = COUNT_OWNERS;
				}
				else
					if ( SMS_Sender_Manager__SendTo == LIST_USERS_GROUP_1 )
					{
						Amount = COUNT_USERS;
					}
				Address = SMS_Sender_Manager__SendTo;
				SMS_Sender_Manager__State++;
			}
			else
			{
				putsf(" >> NO USERS\r", MODEM_PORT );
				SMS_Sender_Manager__Status = READY;
				break;
			}


 */

/* unsigned char SMS_Read_Messages ( const unsigned char* Read_UnRead, unsigned char* SMS_List ) */
/* { */
/* 	static unsigned char State = 0, Index; */
/* 	unsigned char Response; */
		
/* 	switch ( State ) */
/* 	{ */
/* 		case 0:						  /\* Get messages list  *\/ */
/* 			Response = SMS_Get_List( Read_UnRead, SMS_List );  */
/* 			if ( Response != BUSY ) */
/* 			{ */
/* 				if ( Response != MODEM_ERROR ) */
/* 				{	 */
/* 					if ( Response == 0 ) */
/* 					{ */
/* 						State = 0; */
/* 						return NO_MESSAGES; */
/* 					} */
/* #ifdef   LCD_MODE */
/* 					SMS_ListView.DisplayString = 0; */
/* 					SMS_ListView.Item = 0; */
/* 					//CurrentMenu -> DisplayString = 0; */
/* 					SMS_List_View[0][0] = 0; */
/* 					SMS_List_View[1][0] = 0; */
/* 					SMS_List_View[2][0] = 0; */

/* 					CurrentMenu = &SMS_ListView; */
/* #endif */
					
/* 					SMS_User_New_Message_Count = 0; */
/* 					SMS_User_Ext_New_Message_Count = 0; */

/* 					if ( SIM_CARD == INTERNAL ) */
/* 					{ */
/* 						SMS_User_Free_Entry = SMS_FOR_USER_MAX; */
/* 						SMS_User_Free_Entry -= Response;	/\* Rewrite max. user SMS messages *\/ */
/* 					} */

/* /\* 					SMS_ListView.ItemsCount = Response; *\/ */

/* /\* 					if ( Response < 3  ) /\\* 3 strings only for dislpay *\\/ *\/ */
/* /\* 					{ *\/ */
/* /\* 						SMS_ListView.DisplayStringCount = Response; *\/ */
/* /\* 					} *\/ */
/* /\* 					else *\/ */
/* /\* 					{ *\/ */
/* /\* 						SMS_ListView.DisplayStringCount = 3; *\/ */
/* /\* 					} *\/ */

/* 					Index = 0; */
/* 					State++; */
/* 				} */
/* 				else */
/* 				{ */
/* 					State = 0; */
/* 					return FALSE; */
/* 				} */
/* 			} */
/* 			break; */

/* 		case 1: */
/* 			//Response = SMS_Read( SMS_Buffer, SMS_List[Index], SMS_SERVICE ) ; */
/* 			Response = SMS_Read( MessageEditor, SMS_List[Index], SMS_SERVICE ) ; */
/* 			if ( Response != BUSY ) */
/* 			{ */
/* 				if ( Response == TRUE ) */
/* 				{ */
/* 					if ( StrLen(MessageEditor) < 16 ) */
/* 					{ */
/* 						StrCpy(SMS_List_View[Index], MessageEditor); */
/* 					} */
/* 					else */
/* 					{ */
/* 						MemCpy(SMS_List_View[Index], MessageEditor, 13); */
/* 						SMS_List_View[Index][13] = 0; */
/* 						StrCat( SMS_List_View[Index], "..."); */
/* 					} */
/* 					State++; */
/* 				} */
/* 				else */
/* 				{ */
/* 					State = 0; */
/* 					return FALSE; */
/* 				} */
/* 			} */

/* 			break; */

/* 		case 2:	/\* Next message. Maximum 3 messages, because on display 3 strings only *\/ */
/* 			if (  Index == 2 || SMS_List[++Index] == 0 ) */
/* 			{ */
/* 				State = 0; */
/* 				return TRUE; */
/* 			} */
/* 			else */
/* 				State--; */

/* /\* 			if ( Index == 2 )	/\\* Next message. Maximum 3 messages because on display 3 strings only*\\/ *\/ */
/* /\* 			{ *\/ */
/* /\* 				State = 0; *\/ */
/* /\* 				return TRUE; *\/ */
/* /\* 			}  *\/ */
/* /\* 			else *\/ */
/* /\* 			{ *\/ */
/* /\* 				Index++; *\/ */
/* /\* 				State--; *\/ */
/* /\* 			} *\/ */
/* 			break; */

/* 		default	: */
/* 			; */
/* 	} */
	
/* 	return BUSY; */

/* } */


/* 

*/
